package com.example.controller;


import com.example.entity.Product;
import com.example.service.productservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/product")
public class productController {
    @Autowired
    @Qualifier("productService")
    private productservice service;

    @RequestMapping("/addProduct")
    private String addProduct(Product product, MultipartFile imgFile, MultipartFile useFile, HttpServletRequest request) throws IOException {
        String pid = UUID.randomUUID().toString();
        product.setPid(pid);
        //存储图片并设置产品img的路径
        String imgName = saveFile(imgFile, pid, request);
        product.setImg("Milo/fileDir/"+imgName);
        //存储使用说明书并设置其路径
        String useName = saveFile(useFile, pid, request);
        product.setDescription("Milo/fileDir/"+useName);
        //存储数据库
        service.insert(product);
        //给页面绑定数据
        request.setAttribute("product",product);
        return "productinfo";
    }
    private String saveFile(MultipartFile file,String pid,HttpServletRequest request) throws IOException {
        //截取文件后缀名,生成新的文件名字
        String filename = file.getOriginalFilename();
        String ext = filename.substring(filename.lastIndexOf("."));
        String fileSaveName= pid+"_"+System.currentTimeMillis()+ext;
        //获取img目录在服务器的路径
        String fileSavePath = request.getServletContext().getRealPath("Milo/fileDir");
        //构建存储路径
        String savePath =fileSavePath+"/"+fileSaveName;
        //存储文件
        file.transferTo(new File(savePath));

        return fileSaveName;
    }
    @RequestMapping("/fileup")
    public String fileDemo(){
        return "productup";
    }
}
